package com.wsd.serviceImpl;

import com.wsd.dao.LoanInformationMapper;
import com.wsd.dao.RepaymentPlanMapper;
import com.wsd.domain.LoanDetails;
import com.wsd.domain.LoanInformation;
import com.wsd.domain.RepaymentPlan;
import com.wsd.service.LoanInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class LoanInformationServiceImpl implements LoanInformationService {
    @Autowired
    private LoanInformationMapper loanInformationMapper;
    @Autowired
    private RepaymentPlanMapper repaymentPlanMapper;
    @Autowired
    private LoanDetails loanDetails;

    /**
     * 根据客户编号查找贷款信息
     *
     * @param customerId
     * @return
     */
    @Override
    public List<LoanInformation> selectLoanByCustomerId(String customerId) {
        long id = Long.parseLong(customerId);
        List<LoanInformation> list = loanInformationMapper.selectLoanByCustomerId(id);
        return list;
    }

    @Override
    public LoanDetails selectLoanDetailsByLoanId(long loanId) {
        LoanInformation loanInformation = loanInformationMapper.selectByPrimaryKey(loanId);
        List<RepaymentPlan> repaymentPlans = repaymentPlanMapper.selectRepaymentPlanByLoanId(loanId);
        loanDetails.setLoanAmount(loanInformation.getLoanAmount());
        loanDetails.setInstallmentNum(Integer.valueOf(loanInformation.getInstallmentNum()));
        loanDetails.setRepaymentType(loanInformation.getRepaymentType().charAt(0));
        loanDetails.setLoanId(loanId);
        loanDetails.setCustomerId(loanInformation.getCustomerId());
        /*定义已还本金利息累加器*/
        BigDecimal interestCount = new BigDecimal("0");
        BigDecimal returnInterestCount = new BigDecimal("0");
        BigDecimal returnPrincipalCount = new BigDecimal("0");
        BigDecimal overdueInterestCount = new BigDecimal("0");
        for (RepaymentPlan repaymentPlan : repaymentPlans) {
            if (repaymentPlan.getRepaymentStatus().equals("1")) {
                returnInterestCount = returnInterestCount.add(repaymentPlan.getInterestPart());
                returnPrincipalCount = returnPrincipalCount.add(repaymentPlan.getPrincipalPart());
            }
            if (repaymentPlan.getRepaymentStatus().equals("2")) {
                overdueInterestCount = overdueInterestCount.add(repaymentPlan.getOverdueInterest());
            }
            interestCount = interestCount.add(repaymentPlan.getInterestPart());
        }
        loanDetails.setOverdueInterest(overdueInterestCount);
        loanDetails.setReturnInterest(returnInterestCount);
        loanDetails.setReturnPrincipal(returnPrincipalCount);
        loanDetails.setUsedPrincipal(loanInformation.getLoanAmount().subtract(returnPrincipalCount));
        loanDetails.setLoanInterest(interestCount.add(overdueInterestCount));
        return loanDetails;
    }
}
